const express = require('express')
const { userService } = require('../services')
const { authMiddleware } = require('../middlewares/authMiddleware')

// 创建路由器
const authRouter = express.Router() // 处理认证相关路由

// 用户注册
authRouter.post('/register', async (req, res) => {
  try {
    const userData = req.body
    const user = await userService.createUser(userData)
    res.status(201).json({
      success: true,
      message: '用户注册成功',
      data: user,
    })
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message || '用户注册失败',
      error: error.message,
    })
  }
})

// 用户登录
authRouter.post('/login', async (req, res) => {
  try {
    const account = req.body.account
    const password = req.body.password
    if (!account || !password) {
      return res.status(400).json({
        success: false,
        message: '账号和密码不能为空',
        error: '账号和密码不能为空',
      })
    }
    const result = await userService.login(account, password)
    res.status(200).json({
      success: true,
      message: '登录成功',
      data: result,
    })
  } catch (error) {
    res.status(401).json({
      success: false,
      message: error.message || '登录失败',
      error: error.message,
    })
  }
})

// 获取当前登录用户信息
authRouter.get('/profile', authMiddleware, async (req, res) => {
  try {
    const user = await userService.getUserById(req.user.id)
    res.status(200).json({
      success: true,
      data: user,
    })
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message || '获取用户信息失败',
      error: error.message,
    })
  }
})

module.exports = {
  authRouter,
}
